package com.flashmoment.video.controller;

import ch.qos.logback.core.util.FileUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.flashmoment.video.entity.VideoEntity;
import com.flashmoment.video.service.VideoService;
import com.flashmoment.video.utils.MinioUtils;
import com.flashmoment.video.utils.R;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.FileUtils;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import com.qiniu.http.Client;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.Buffer;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@Log4j2
@RequestMapping("video/updata")
@Api(tags = "上传")
public class UpDataController {

    @Value("${qiniuyun.accessKey}")
    private String accessKey;
    @Value("${qiniuyun.secretKey}")
    private String secretKey;
    @Value("${qiniuyun.bucket}")
    private String bucket;
    @Value(("${qiniuyun.videoUrl}"))
    private String videoUrl;
    @Value(("${qiniuyun.imgUrl}"))
    private String imgUrl;
    @Autowired
    private MinioUtils minioUtils;
    @Autowired
    VideoService videoService;
    @RequestMapping("/getUpToken")
    public Map<String,String>getUpToken(){
        Auth auth = Auth.create(accessKey, secretKey);
        StringMap stringMap = new StringMap();
        String uploadToken = auth.uploadToken(bucket,null,1000L,stringMap);
        Map<String, String> uploadTokenMap = new HashMap<>();
        uploadTokenMap.put("uploadToken",uploadToken);
        return uploadTokenMap;
    }

//    http://s32hava72.bkt.clouddn.com/82ebfa60f7c6def65ccd45af07c15da2.mp4
@PostMapping("/uploadFile")
public R uploadFile(@RequestPart("file") MultipartFile file, HttpServletRequest request) {
    // 获取文件名和文件扩展名
    String fileName = file.getOriginalFilename();
    String prefix = fileName.substring(fileName.lastIndexOf("."));
    // 生成新的文件名，以避免同名文件覆盖
    String uuid = "v_" + UUID.randomUUID().toString().replaceAll("-", "") + prefix;

    // 设置要保存文件的本地路径，这里需要根据实际情况进行设置
    String savePath = "E:" + File.separator + "design" + File.separator + uuid;
    // 确保保存路径存在，如果不存在则创建
    File dir = new File(savePath).getParentFile();
    if (!dir.exists()) {
        dir.mkdirs();
    }

    try {
        // 将文件保存到本地文件系统
        file.transferTo(new File(savePath));

        // 创建视频实体并设置属性
        VideoEntity videoEntity = new VideoEntity();
        videoEntity.setVideoName(uuid);
        videoEntity.setVideoUrl(savePath); // 假设本地视频访问路径为 /local/
        videoEntity.setCreateTime(DateUtil.date());
        videoEntity.setUpdateTime(DateUtil.date());
        videoEntity.setVideoUser(request.getParameter("userId"));
        videoEntity.setVideoContent(request.getParameter("content"));
        videoEntity.setVideoType(Integer.valueOf(request.getParameter("type")));
        videoEntity.setStatus(Integer.valueOf(request.getParameter("state")));
        videoEntity.setVideoTitle(request.getParameter("title"));
        videoEntity.setVideoName(fileName);
        // 如果需要，可以设置其他属性

        // 保存视频实体到数据库
        boolean save = videoService.save(videoEntity);
        if (!save) {
            return R.error("视频保存失败");
        }
    } catch (IOException e) {
        e.printStackTrace();
        log.error(e);
        return R.error("文件上传失败");
    }

    return R.ok().put("msg", "上传成功");
}
    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam(name = "file", required = false) MultipartFile file, HttpServletRequest request) {
        JSONObject res = null;
        try {
            res = minioUtils.uploadFile(file, "video");
            String uuid = "v_" + UUID.randomUUID().toString().replaceAll("-", "");

            VideoEntity videoEntity = new VideoEntity();
            videoEntity.setVideoName(file.getOriginalFilename());
            videoEntity.setVideoUrl((String) res.get("msg")); // 假设本地视频访问路径为 /local/
            videoEntity.setCreateTime(DateUtil.date());
            videoEntity.setUpdateTime(DateUtil.date());
            videoEntity.setVideoUser(request.getParameter("userId"));
            videoEntity.setVideoContent(request.getParameter("content"));
            videoEntity.setVideoType(Integer.valueOf(request.getParameter("type")));
            videoEntity.setStatus(Integer.valueOf(request.getParameter("state")));
            videoEntity.setVideoTitle(request.getParameter("title"));
            // 如果需要，可以设置其他属性

            // 保存视频实体到数据库
            boolean save = videoService.save(videoEntity);

        } catch (Exception e) {
            e.printStackTrace();
            res.put("code", 0);
            res.put("name", UUID.randomUUID());
            res.put("msg", "上传失败");
        }
        return res.toJSONString();
    }

    @PostMapping("/uploadImg")
    @ResponseBody
    public String uploadImg(@RequestParam(name = "file", required = false) MultipartFile file, HttpServletRequest request) {
        JSONObject res = null;
        try {
            res = minioUtils.uploadFile(file, "edc-istudy");
        } catch (Exception e) {
            e.printStackTrace();
            res.put("code", 0);
            res.put("name", UUID.randomUUID());
            res.put("msg", "上传失败");
        }
        return res.toJSONString();
    }

}
